import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import { 
  Button, 
  Tabs, 
  Grid, 
  Card,
  Swiper,
  Skeleton
} from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import TopNavbar from '../../components/TopNavbar'
import BottomNav from '../../components/BottomNav'
import ReactNativeWrapper from '../../components/ReactNativeWrapper'
import ReactNativeAdvanced from '../../components/ReactNativeAdvanced'
import styles from './index.module.css'
import { fetchHomeConfig, fetchUserHomeStatus, openBannerTarget, fetchArticles } from '../../services/homeService'
import { logClick, logExposure } from '../../services/tracking'

const Home = () => {
  const navigate = useNavigate()
  const [currentTab, setCurrentTab] = useState(() => {
    if (typeof window !== 'undefined' && window.localStorage) {
      const val = window.localStorage.getItem('homeTab')
      return val || 'outpatient'
    }
    return 'outpatient'
  })
  const [announcementIndex, setAnnouncementIndex] = useState(0)
  const [isLoading, setIsLoading] = useState(true)
  const [banners, setBanners] = useState([])
  const [services, setServices] = useState([])
  const [userStatus, setUserStatus] = useState(null)
  const [announcements, setAnnouncements] = useState([])
  const [articles, setArticles] = useState([])
  const [articlePage, setArticlePage] = useState(1)
  const [hasMoreArticles, setHasMoreArticles] = useState(true)
  const [isLoadingMore, setIsLoadingMore] = useState(false)
  const [showAdvancedRN, setShowAdvancedRN] = useState(false)
  const sentinelRef = useRef(null)

  // refs for exposure tracking
  const bannerRefs = useRef({})
  const serviceRefs = useRef({})
  const exposedBannerIds = useRef(new Set())
  const exposedServiceKeys = useRef(new Set())

  // 公告滚动效果
  useEffect(() => {
    const timer = setInterval(() => {
      const total = announcements && announcements.length ? announcements.length : 1
      setAnnouncementIndex(prev => (prev + 1) % total)
    }, 2000)
    return () => clearInterval(timer)
  }, [announcements])

  // 首屏数据加载
  useEffect(() => {
    let mounted = true
    setIsLoading(true)
    Promise.all([
      fetchHomeConfig(),
      fetchUserHomeStatus()
    ])
      .then(([config, status]) => {
        if (!mounted) return
        setBanners(config.banners || [])
        setServices(config.services || [])
        setAnnouncements(config.announcements || [])
        setArticles([])
        setUserStatus(status || null)
        logExposure('首页首屏渲染', { 横幅数量: (config.banners || []).length, 服务数量: (config.services || []).length })
      })
      .finally(() => mounted && setIsLoading(false))
    return () => { mounted = false }
  }, [])

  // 记忆当前所选Tab
  useEffect(() => {
    if (typeof window !== 'undefined' && window.localStorage) {
      window.localStorage.setItem('homeTab', currentTab)
    }
  }, [currentTab])

  // 首次与分页加载文章
  useEffect(() => {
    let mounted = true
    fetchArticles({ page: 1, pageSize: 5 }).then(({ items, hasMore }) => {
      if (!mounted) return
      setArticles(items || [])
      setArticlePage(1)
      setHasMoreArticles(!!hasMore)
    })
    return () => { mounted = false }
  }, [])

  const loadMoreArticles = useCallback(() => {
    if (!hasMoreArticles || isLoadingMore) return
    setIsLoadingMore(true)
    const next = articlePage + 1
    fetchArticles({ page: next, pageSize: 5 }).then(({ items, hasMore }) => {
      setArticles(prev => [...prev, ...(items || [])])
      setArticlePage(next)
      setHasMoreArticles(!!hasMore)
    }).finally(() => setIsLoadingMore(false))
  }, [articlePage, hasMoreArticles, isLoadingMore])

  // React Native 组件导航处理
  const handleReactNativeNavigation = useCallback((action) => {
    logClick('React Native 组件点击', { action })
    switch (action) {
      case 'emergency':
        navigate('/emergency')
        break
      case 'appointment':
        navigate('/appointment')
        break
      case 'reports':
        navigate('/reports')
        break
      case 'medication':
        navigate('/medication')
        break
      default:
        console.log('Unknown action:', action)
    }
  }, [navigate])

  // 监听底部哨兵实现上拉加载
  useEffect(() => {
    const el = sentinelRef.current
    if (!el) return
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          loadMoreArticles()
        }
      })
    }, { root: null, threshold: 0.1 })
    observer.observe(el)
    return () => observer.disconnect()
  }, [loadMoreArticles])

  const visibleServices = useMemo(() => {
    const map = {
      outpatient: 'outpatient',
      inpatient: 'inpatient',
      comprehensive: 'comprehensive'
    }
    const category = map[currentTab] || 'outpatient'
    const filtered = services.filter(s => (s.category || 'outpatient') === category)
    return filtered.slice(0, 8)
  }, [services, currentTab])

  // Exposure tracking: observe banners and services once loaded
  useEffect(() => {
    if (isLoading) return
    const observers = []

    const createObserver = (type) => new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting && entry.intersectionRatio >= 0.5) {
          if (type === 'banner') {
            const id = entry.target.getAttribute('data-id')
            if (id && !exposedBannerIds.current.has(id)) {
              exposedBannerIds.current.add(id)
              logExposure('banner_exposure', { id })
            }
          } else if (type === 'service') {
            const key = entry.target.getAttribute('data-key')
            if (key && !exposedServiceKeys.current.has(key)) {
              exposedServiceKeys.current.add(key)
              logExposure('service_exposure', { key })
            }
          }
        }
      })
    }, { threshold: [0.5] })

    const bannerObserver = createObserver('banner')
    const serviceObserver = createObserver('service')
    observers.push(bannerObserver, serviceObserver)

    Object.values(bannerRefs.current).forEach(el => el && bannerObserver.observe(el))
    Object.values(serviceRefs.current).forEach(el => el && serviceObserver.observe(el))

    return () => {
      observers.forEach(o => o.disconnect())
    }
  }, [isLoading, banners, visibleServices])

  return (
    <div className={styles.app}>
      {/* 固定顶部导航 */}
      <TopNavbar
        title="智慧医院"
        rightContent={
          <>
            <span>🔍</span>
            <span>🔔</span>
          </>
        }
      />

      {/* 轮播图横幅 */}
      <div className={styles.bannerSection}>
        {isLoading ? (
          <div className={styles.bannerSlide}>
            <Skeleton animated style={{ width: '100%', height: '100%' }} />
          </div>
        ) : (
          <Swiper autoplay loop>
            {banners.map(item => (
              <Swiper.Item key={item.id}>
                <div 
                  className={styles.bannerSlide}
                  style={{ backgroundColor: item.color || '#4CAF50' }}
                  data-id={item.id}
                  ref={el => { bannerRefs.current[item.id] = el }}
                  onClick={() => {
                    logClick('横幅点击', { id: item.id, 跳转类型: item.jumpType })
                    openBannerTarget(navigate, item)
                  }}
                >
                  <div className={styles.bannerContent}>
                    <div className={styles.bannerText}>
                      <h1>{item.title}</h1>
                    </div>
                    <div className={styles.bannerIllustration}>
                      <div className={styles.doctorIcon}>👨‍⚕️</div>
                      <div className={styles.medicalItems}>
                        <span>💉</span>
                        <span>📅</span>
                      </div>
                    </div>
                  </div>
                </div>
              </Swiper.Item>
            ))}
          </Swiper>
        )}
      </div>

      {/* 主要功能按钮 */}
      <div className={styles.mainActions}>
        <div className={styles.actionRow}>
          <Button 
            className={`${styles.actionBtn} ${styles.registration}`}
            block
            size="large"
          onClick={() => navigate('/register/notice')}
          >
            <div className={styles.btnContent}>
              <div className={styles.btnIcon}>
                📅
                ✅
              </div>
              <div className={styles.btnText}>
                <div className={styles.btnTitle}>门诊挂号</div>
                <div className={styles.btnSubtitle}>便捷预约挂号</div>
              </div>
            </div>
          </Button>
          
          <Button 
            className={`${styles.actionBtn} ${styles.payment}`}
            block
            size="large"
            onClick={() => navigate('/payment')}
          >
            <div className={styles.btnContent} >
              <div className={styles.btnIcon}>
                💰
              </div>
              <div className={styles.btnText}>
                <div className={styles.btnTitle}>门诊缴费</div>
                <div className={styles.btnSubtitle}>便捷预约挂号</div>
              </div>
            </div>
          </Button>
        </div>
      </div>

      {/* 滚动公告栏 */}
      <div className={styles.announcement}>
        <div className={styles.announcementLabel}>公告</div>
        <div className={styles.announcementContent}>
          <div className={styles.announcementText}>
            {announcements[announcementIndex] || '欢迎使用智慧医院服务'}
          </div>
          <span className={styles.arrow}>→</span>
        </div>
      </div>

      {/* 服务导航标签 */}
      <div className={styles.serviceTabs}>
        <Tabs 
          activeKey={currentTab} 
          onChange={setCurrentTab}
          className={styles.customTabs}
        >
          <Tabs.Tab title="门诊" key="outpatient" />
          <Tabs.Tab title="住院" key="inpatient" />
          <Tabs.Tab title="综合" key="comprehensive" />
        </Tabs>
        <div 
          className={styles.moreLink}
          onClick={() => navigate('/menu')}
        >
          更多
        </div>
      </div>

      {/* 个性化状态 */}
      {!isLoading && userStatus && (
        <div className={styles.statusChips}>
          {userStatus.hasPendingPayment && (
            <div className={styles.statusChip} onClick={() => navigate('/payment')}>
              您有待缴费订单（{userStatus.pendingPaymentCount}）
            </div>
          )}
          {userStatus.hasTodayRegistration && (
            <div className={styles.statusChip} onClick={() => navigate('/register')}>
              今日有挂号（{userStatus.todayRegistrations}）
            </div>
          )}
        </div>
      )}

      {/* 服务网格 */}
      <div className={styles.serviceGrid}>
        {isLoading ? (
          <Grid columns={4} gap={8}>
            {Array.from({ length: 8 }).map((_, idx) => (
              <Grid.Item key={idx}>
                <div className={styles.serviceItem}>
                  <Skeleton animated style={{ width: 24, height: 24, borderRadius: 12, margin: '0 auto 8px' }} />
                  <Skeleton.Paragraph lineCount={1} animated style={{ width: 60, height: 12, margin: '0 auto' }} />
                </div>
              </Grid.Item>
            ))}
          </Grid>
        ) : (
          <Grid columns={4} gap={8}>
            {visibleServices.map((item) => (
              <Grid.Item key={item.key}>
                <div className={styles.serviceItem} data-key={item.key} ref={el => { serviceRefs.current[item.key] = el }} onClick={() => {
                  logClick('服务点击', { 标识: item.key })
                  if (item.path) navigate(item.path)
                }}>
                  <div className={styles.serviceIcon}>{item.icon}</div>
                  <div className={styles.serviceText}>{item.text}</div>
                </div>
              </Grid.Item>
            ))}
          </Grid>
        )}
      </div>

      {/* React Native 组件区域 */}
      {!isLoading && (
        <div className={styles.reactNativeSection}>
          <div className={styles.rnHeader}>
            <h3>React Native 组件</h3>
            <Button 
              size="small"
              onClick={() => setShowAdvancedRN(!showAdvancedRN)}
            >
              {showAdvancedRN ? '基础版' : '高级版'}
            </Button>
          </div>
          {showAdvancedRN ? (
            <ReactNativeAdvanced onNavigate={handleReactNativeNavigation} />
          ) : (
            <ReactNativeWrapper onNavigate={handleReactNativeNavigation} />
          )}
        </div>
      )}

      {/* 智能客服浮动按钮 */}
      <div className={styles.floatingService}>
        <Button 
          className={styles.serviceBtn}
          shape="circle"
          size="large"
          onClick={() => navigate('/customer-service')}
        >
          💬
          <div className={styles.serviceLabel}>智能客服</div>
        </Button>
      </div>

      {/* 健康资讯 */}
      <div className={styles.healthInfo}>
        <div className={styles.infoHeader}>
          <h3>健康资讯</h3>
          <div 
            className={styles.moreBtn}
            onClick={() => navigate('/health')}
          >
            更多
          </div>
        </div>
        {isLoading ? (
          Array.from({ length: 3 }).map((_, idx) => (
            <Card className={styles.infoCard} key={idx}>
              <div className={styles.infoContent}>
                <Skeleton.Paragraph animated lineCount={2} style={{ width: '70%' }} />
                <div className={styles.infoImage}>
                  <Skeleton animated style={{ width: 60, height: 60, borderRadius: 8 }} />
                </div>
              </div>
              <div className={styles.infoFooter}>
                <span className={styles.infoTag}><Skeleton animated style={{ width: 60, height: 16 }} /></span>
                <div className={styles.infoStats}>
                  <span><Skeleton animated style={{ width: 40, height: 12 }} /></span>
                  <span><Skeleton animated style={{ width: 40, height: 12 }} /></span>
                </div>
              </div>
            </Card>
          ))
        ) : (
          (articles && articles.length > 0) && (
            articles.map(article => (
              <Card className={styles.infoCard} key={article.id} onClick={() => navigate(`/health/${article.id}`)}>
                <div className={styles.infoContent}>
                  <div className={styles.infoTitle}>
                    {article.title}
                  </div>
                  <div className={styles.infoImage}>{article.emoji}</div>
                </div>
                <div className={styles.infoFooter}>
                  <span className={styles.infoTag}>{article.tag}</span>
                  <div className={styles.infoStats}>
                    <span>👍 {article.likes}</span>
                    <span>👁️ {article.views}</span>
                  </div>
                </div>
              </Card>
            ))
          )
        )}
      </div>
      {/* 列表底部状态 */}
      <div className={styles.listFooter}>
        {isLoadingMore ? '加载中...' : (!hasMoreArticles ? '没有更多了' : '')}
      </div>
      {/* 上拉加载 哨兵 */}
      <div ref={sentinelRef} style={{ height: 1 }} />

      {/* 底部导航 */}
      <BottomNav />
    </div>
  )
}

export default Home
